// var getData = [{"id":0,"n":"A1","x":"10","y":"10","w":"80","h":"20","r":"0"},{"id":1,"n":"A1","x":"10","y":"40","w":"80","h":"20","r":"0"},{"id":2,"n":"A1","x":"10","y":"70","w":"80","h":"20","r":"0"},{"id":3,"n":"A1","x":"10","y":"100","w":"80","h":"20","r":"0"},{"id":4,"n":"A1","x":"10","y":"130","w":"80","h":"20","r":"0"},{"id":5,"n":"A1","x":"10","y":"160","w":"80","h":"20","r":"0"},{"id":6,"n":"A1","x":"10","y":"190","w":"80","h":"20","r":"0"},{"id":7,"n":"A1","x":"10","y":"220","w":"80","h":"20","r":"0"},{"id":8,"n":"A1","x":"10","y":"250","w":"80","h":"20","r":"0"},{"id":9,"n":"A1","x":"10","y":"280","w":"80","h":"20","r":"0"},{"id":10,"n":"A1","x":"10","y":"310","w":"80","h":"20","r":"0"},{"id":11,"n":"A1","x":"10","y":"340","w":"80","h":"20","r":"0"},{"id":12,"n":"A1","x":"10","y":"370","w":"80","h":"20","r":"0"},{"id":13,"n":"A1","x":"10","y":"400","w":"80","h":"20","r":"0"},{"id":14,"n":"A1","x":"10","y":"430","w":"80","h":"20","r":"0"}];

// let dev = /http:\/\/localhost/.test(window.location.href);
let dev = true;
console.log(dev);

window.onload = function() {
  let btnOpen = document.querySelector('.btn-open');
  let navigation = document.querySelector('.navigation');
  let btnCreate = document.querySelector('.btn-create');
  let btnSave = document.querySelector('.btn-save');
  let room = document.querySelector('.room');
  let controls = document.querySelectorAll('.control-panel div input');
  let boxAttr = document.querySelector('.box-attr');

  // 边界
  let boundary = {
    w: room.offsetWidth - parseInt(getStyle(room, 'borderWidth')) * 2,
    h: room.offsetHeight - parseInt(getStyle(room, 'borderWidth')) * 2
  };

  let arr = [];

  // 载入已保存数据
  if(dev) {
    let getData = localStorage.shelfPos || '[]';
    drawShelf(JSON.parse(getData));
    // drawShelf(JSON.parse(getData));
  } else {
    drawShelf(strJson);
  }

  // btnOpen.onclick = () => {
  //   navigation.style.opacity = '1';
  // }

  // 点击创建按钮
  btnCreate.onclick = () => {
    let options = [{
      w: controls[0].value,
      h: controls[1].value,
      x: controls[2].value,
      y: controls[3].value,
      r: controls[4].value,
      n: controls[5].value,
      id: new Date().getTime()
    }];
    drawShelf(options);
    // let div1 = new Box(options);
    // div1.id = arr.length;
    // arr.push(div1);       // 将对象放入数组
    // div1.showBox(room);   // 对象插入room
    // div1.drag(boundary);  // 对象拖拽
    // // 对象右键菜单
    // div1.ele.oncontextmenu = function(ev) {
    //   console.log(arr);
    //   let oEvent = ev || event;
    //   boxAttr.style.display = 'block';
    //   boxAttr.style.left = oEvent.clientX + 'px';
    //   boxAttr.style.top = oEvent.clientY + 'px';
    //   boxAttr.innerHTML = `
    //   <p>名称: ${div1.n}</p>
    //   <p>ID: ${div1.id}</p>
    //   <p>宽度: ${div1.w}</p>
    //   <p>高度: ${div1.h}</p>
    //   <p>坐标x: ${div1.x}</p>
    //   <p>坐标y: ${div1.y}</p>
    //   <p>旋转: ${div1.r}</p>
    //   <input type="button" value="删除" class="deleteobj" />
    //   `;
    //
    //   // 删除按钮
    //   let btnDelete = document.querySelector('.deleteobj');
    //   btnDelete.onclick = () => {
    //     let index = arr.indexOf(div1);
    //     // console.log(index);
    //     arr.splice(index,1);
    //
    //     room.removeChild(div1.ele);
    //     boxAttr.innerHTML = '';
    //     boxAttr.style.display = 'none';
    //   }
    //
    //
    //   return false;
    // };

  }
  // 保存按钮
  btnSave.onclick = () => {
    var shelfData = [];
    for (let i = 0; i < arr.length; i++) {
      let json = JSON.parse(JSON.stringify(arr[i]));
      delete json.ele;
      shelfData.push(json);
    }

    if(dev) {
      console.log(shelfData)
      localStorage.shelfPos = JSON.stringify(shelfData);
    } else {
      var thedata = "shelfData=" + JSON.stringify(shelfData);

      $.ajax({
          type: "POST",
          url: window.location.href,
          data: thedata
      }).done(function (contents) {
          alert('保存成功');
          window.close();
      }).fail(function (data) {
        // Optionally alert the user of an error here...
        window.close();
      });

      arr = shelfData;
    }
  }

  document.body.onclick = () => {
    boxAttr.style.display = 'none';
  }
  boxAttr.onclick = (ev) => {
    let oEvent = ev || event;
    oEvent.cancelBubble = true;
  }

  function drawShelf(data) {
    let temarr = data;
    for(let i = 0; i < temarr.length; i++) {
      let divBox = new Box(temarr[i]);
      // divBox.id = arr.length;
      arr.push(divBox);       // 将对象放入数组
      divBox.showBox(room);   // 对象插入room
      divBox.drag(boundary);  // 对象拖拽
      // 对象右键菜单
      divBox.ele.oncontextmenu = function(ev) {
        // console.log(arr);
        let oEvent = ev || event;
        // console.log(oEvent.clientY);
        boxAttr.style.display = 'block';
        boxAttr.style.left = oEvent.clientX + 'px';

        // 菜单位置弹出处理
        if(document.documentElement.clientHeight - oEvent.clientY < 280) {
          boxAttr.style.top = oEvent.clientY - 280 + 'px';
        } else {
          boxAttr.style.top = oEvent.clientY + 'px';
        }

        boxAttr.innerHTML = `
        <p>名称: <span>${divBox.n}</span></p>
        <p>ID: <span>${divBox.id}</span></p>
        <p>宽度: <span>${divBox.w}</span></p>
        <p>高度: <span>${divBox.h}</span></p>
        <p>坐标 x:
          <input type="text" class="x" value="${divBox.x}" />
        </p>
        <p>坐标 y:
          <input type="text" class="y" value="${divBox.y}" />
        </p>
        <p>旋转:
          <input type="text" class="r" value="${divBox.r}" />
        </p>
        <input type="button" value="删除" class="deleteobj" />
        <input type="button" value="修改" class="confirm" />
        `;

        // x+
        // document.querySelector('.plusx').onclick = () => {
        //   divBox.x++;
        //   if (divBox.x <= 0) divBox.x = 0;
        //   if (divBox.x >= boundary.w - divBox.ele.offsetWidth) divBox.x = boundary.w - divBox.ele.offsetWidth;
        //   document.querySelector('.x').value = divBox.x;
        //   divBox.ele.style.left = divBox.x + 'px';
        // };

        // 修改按钮
        // 回车
        document.querySelector('.x').onkeyup = ev => {
          let oEvent = ev || event;
          if(ev.keyCode == '13') {
            fnConfirm();
          }
        };
        document.querySelector('.y').onkeyup = ev => {
          let oEvent = ev || event;
          if(ev.keyCode == '13') {
            fnConfirm();
          }
        };
        document.querySelector('.r').onkeyup = ev => {
          let oEvent = ev || event;
          if(ev.keyCode == '13') {
            fnConfirm();
          }
        };
        // 点击修改
        document.querySelector('.confirm').onclick = fnConfirm;

        function fnConfirm() {
          let x = parseInt(document.querySelector('.x').value);
          let y = parseInt(document.querySelector('.y').value);
          let r = parseInt(document.querySelector('.r').value);

          if (x <= 0) x = 0;
          if (y <= 0) y = 0;
          if (x >= boundary.w - divBox.ele.offsetWidth) x = boundary.w - divBox.ele.offsetWidth;
          if (y >= boundary.h - divBox.ele.offsetHeight) y = boundary.h - divBox.ele.offsetHeight;

          divBox.x = x;
          divBox.y = y;
          divBox.r = r;

          divBox.ele.style.left = x + 'px';
          divBox.ele.style.top = y + 'px';
          divBox.ele.style.transform = `rotate(${r}deg)`;

          boxAttr.style.display = 'none';
        }

        // 删除按钮
        let btnDelete = document.querySelector('.deleteobj');

        btnDelete.onclick = () => {
          let index = arr.indexOf(arr[i]);
          arr.splice(index,1);

          room.removeChild(divBox.ele);
          boxAttr.innerHTML = '';
          boxAttr.style.display = 'none';
        }

        return false;
      };
    }
  }
};


class Box {
  constructor(options) {
    // this.bg = options.bg || 'orange';
    this.id = options.id;
    this.n = options.n || 0;
    this.x = options.x || 0;
    this.y = options.y || 0;
    this.w = options.w || '80';
    this.h = options.h || '20';
    this.r = options.r || 0;
    // this.scale=options.scale||1;
    this.ele = null;
  }

  showBox(parent) {
    let oDiv = document.createElement('div');
    oDiv.className = 'bookshelf';
    oDiv.style.width = isNaN(this.w) ? this.w : this.w + 'px';
    oDiv.style.height = isNaN(this.h) ? this.h : this.h + 'px';
    oDiv.style.background = this.bg;
    oDiv.style.left = isNaN(this.x) ? this.x : this.x + 'px';
    oDiv.style.top = isNaN(this.y) ? this.y : this.y + 'px';
    oDiv.style.transform = `rotate(${this.r}deg)`;

    this.ele = oDiv;
    parent.appendChild(oDiv);
  }

  drag(range) {
    let x = this.x;
    let y = this.y;
    this.ele.onmousedown = (ev) => {
      x = this.x;
      y = this.y;
      let oEvent = ev || event;
      let disX = oEvent.clientX - x;
      let disY = oEvent.clientY - y;
      // console.log(disX,disY);
      let startX = oEvent.clientX;
      let startY = oEvent.clientY;
      let ele = this.ele;

      if (this.ele.setCapture) {
        this.ele.onmousemove = mouseMove.bind(this);
        this.ele.onmouseup = mouseUp;
        this.ele.setCapture();
      } else {
        document.onmousemove = mouseMove.bind(this);
        document.onmouseup = mouseUp;
      }


      function mouseMove(ev) {
        // console.log(this);
        let oEvent = ev || event;
        x = oEvent.clientX - disX;
        y = oEvent.clientY - disY;
        if (x <= 0) x = 0;
        if (y <= 0) y = 0;
        if (x >= range.w - this.ele.offsetWidth) x = range.w - this.ele.offsetWidth;
        if (y >= range.h - this.ele.offsetHeight) y = range.h - this.ele.offsetHeight;

        this.ele.style.left = x + 'px';
        this.ele.style.top = y + 'px';
        this.x = x;
        this.y = y;
      }

      function mouseUp() {
        this.onmousemove = null;
        this.onmouseup = null;
        this.releaseCapture && this.releaseCapture();
      }

      return false;
    }
  }

  outPutAttr() {}
}
